package com.water.fish.widget

import android.animation.Animator
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.animation.LinearInterpolator
import androidx.appcompat.widget.AppCompatImageView
import com.water.fish.R

/**
 *  Created by zxn on 2022/4/28.
 **/
class FoodView : AppCompatImageView {

    companion object {
        private const val TAG = "FoodView"
    }

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        setImageResource(R.drawable.snow_flake)
    }

    private var mFallEndListener: ((FoodView) -> Unit)? = null

    /**
     * 当child被父view移除后,回调次函数.
     */
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        Log.i(TAG, "onDetachedFromWindow: ")
    }

    /**
     * 移动至下落的起点坐标位置.
     */
    private fun moveToStart(targetX: Float, targetY: Float) {
        translationX = targetX
        translationY = targetY
    }

    private fun moveToTarget(targetY: Float) {
        animate()
            .translationY(targetY)
            .setDuration(15 * 1000)
            .setInterpolator(LinearInterpolator())
            .withLayer()
            .setListener(object : Animator.AnimatorListener {

                override fun onAnimationStart(animation: Animator) {

                }

                override fun onAnimationEnd(animation: Animator) {
                    mFallEndListener?.invoke(this@FoodView)
                }

                override fun onAnimationCancel(animation: Animator) {

                }

                override fun onAnimationRepeat(animation: Animator) {

                }
            })
            .setStartDelay(0)
            .start()
    }

    /**
     * 洒落食物
     */
    fun fall(startX: Float, startY: Float, endX: Float, endY: Float) {
        moveToStart(startX, startY)
        moveToTarget(endY)
    }

    fun fall(endY: Float, block: (FoodView) -> Unit) {
        mFallEndListener = block
        moveToTarget(endY)
    }

    /**
     * 食物洒落监听
     */
    fun fallEndListener(block: (FoodView) -> Unit) {
        mFallEndListener = block
    }

    fun stopMove() {
        //moveType = PetView.MOVE_STOP
        animate().cancel()
    }

}


